package com.desktop.click.tool.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONUtil;
import com.desktop.click.tool.entity.RobotClickProperties;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Vector;

public class SerializableUtil {
    /**
     * 持久化数据到磁盘
     *
     * @param data 集合数据
     * @return void
     * @date 2023/2/13 10:08
     * @author glq
     */
    public static void saveLocalFile(Vector<RobotClickProperties> data) {
        File file = new File("data.config");
        if (!file.exists()) {
            try {
                file.createNewFile();

            } catch (Exception e) {
                ;
            }

        } else {
            FileUtil.writeBytes(JSONUtil.toJsonStr(data).getBytes(), file);
        }
    }

    /**
     * 取出缓存到磁盘的数据
     *
     * @return java.util.Vector<com.desktop.click.tool.entity.RobotClickProperties>
     * @date 2023/2/13 10:20
     * @author glq
     */
    public static Vector<RobotClickProperties> getDataByLocalFile() {
        File file = new File("data.config");
        List<RobotClickProperties> data = new Vector<>();
        if (!file.exists()) {
            try {
                file.createNewFile();
                FileUtil.writeBytes(JSONUtil.toJsonStr(data).getBytes(), file);

            } catch (Exception e) {

            }
            return new Vector<>();
        } else {
            byte[] bytes = FileUtil.readBytes(file);
            data = JSONUtil.toList(new String(bytes), RobotClickProperties.class);
            return listToVector(data);
        }
    }

    /**
     * list转成Vector
     *
     * @param list
     * @return `java.util.Vector<com.desktop.click.tool.entity.RobotClickProperties>`
     * @date 2023/2/13 10:20
     * @author glq
     */
    public static Vector<RobotClickProperties> listToVector(List<RobotClickProperties> list) {
        Vector<RobotClickProperties> vector = new Vector<>();
        if (list == null || list.size() == 0) {
            return vector;
        }
        if (vector.getClass().getName().equals(list.getClass().getName())) {
            return (Vector<RobotClickProperties>) list;
        }
        vector.addAll(list);
        return vector;
    }
}
